

// 负责操作localStorage
class DataHelper {
    dataKey: string
    primaryKey: string

    constructor(dataKey: string, primaryKey: string) {
        this.dataKey = dataKey
        this.primaryKey = primaryKey
    }

    readData(): any {
        //1.读取本地数据
        let srcData: string | null = localStorage.getItem(this.dataKey)
        //2.将读取的json数组字符串转成数组对象
        let arrData: any = []
        if (srcData != null) {
            arrData = JSON.parse(srcData)
        }
        //3.返回
        return arrData
    }


    saveData(arrData: Array<object>): void {
        //1.数组转成字符串
        let str: string = JSON.stringify(arrData)
        //2.保存到localStorage
        localStorage.setItem(this.dataKey, str)
    }

    addData(conStr: any): number {
        //1.读取
        let arr: any = this.readData()

        //生成id
        let id = arr.length > 0 ? arr[arr.length - 1][this.primaryKey] + 1 : 1

        //2.创建一个评论对象
        let obj: object = {
            content: conStr,
            [this.primaryKey]: id
        }
        arr.push(obj)
        //保存
        this.saveData(arr)
        return id
    }

    removeData(id:number|string):boolean{
        let arr:any = this.readData()
        let index:number =  arr.findIndex((item:any)=>{
            return item[this.primaryKey] == id
        })
        if(index>-1){
            arr.splice(index,1)
            //保存
            this.saveData(arr)
            return true 
        }
        return false
    }

}


export default DataHelper












